package com.hmall.item.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/*********************************************************
 ** 全局格式化 后台<-->前端 的LocalDateTime、LocalDate时间格式
 ** 如果不想使用全局格式，则在类属性上使用@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
 ** 和@JsonFormat(pattern="yyyy-MM-dd", timezone="GMT+8")注解
 ** <br><br>
 ** @ClassName: LocalDateTimeConverter
 ** @author: yangfeng
 ** @date: 2024/12/16 14:39
 ** @version: 1.0.0
 *********************************************************/
//@Configuration
public class LocalDateTimeSerializerConfig {

    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * localDateTime 序列化器,后台返回给前端时间格式化
     * @return
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeSerializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN));
    }

    /**
     * localDateTime 反序列化器，前端传给后台时间格式化
     * @return
     */
    @Bean
    public LocalDateTimeDeserializer localDateTimeDeserializer() {
        return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN));
    }

    /**
     *
     * @return
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
            builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer());
        };
    }
}
